<template>
  <div style="width: 100%;" v-cloak>
    <!-- TODO:multiple：是否多选，disable-branch-nodes：父节点禁用，前置组件传值 -->
    <treeselect :options="originTree[0] ? originTree : treeDataOptions" :normalizer="normalizer"
      :multiple="selectMultiple" default-expand-all :disable-branch-nodes="disableBranchNodes" placeholder="请选择"
      :default-expand-level="defaultExpandLevel" size="medium" :flat="isFlat" clearValueText="清空当前选择项"
      clearAllText="清空所有选择项" noResultsText="未匹配到数据项" :showCount="showcount" style="width: 100%;" :limit="limit1"
      :limitText="limitTextValue" v-model="selectedTree" @select="selectTree" @deselect="desselectTree"
      :disabled="disabled">
      <label slot="option-label" slot-scope="{ node }">
        <span :title="node.label">{{ node.label }}</span>
      </label>
    </treeselect>
  </div>
</template>
<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import request from '@/utils/request'
import store from '@/store/index'
import { getFunNo } from '@/utils/party'

export default {
  // 99 是作为组织树的级别选择出现的，所以在整个文件中，属于特例。
  name: 'MisSelectTree',
  components: { Treeselect },
  props: {
    // 是否多选
    selectMultiple: {
      type: Boolean,
      default: false,
    },
    // 树类型
    misTreeType: {
      type: [Number, String],
      default: null,
    },
    // 默认值
    setValue: {
      type: [Number, String, Array],
      default: null,
    },
    // 是否根节点可选
    disableBranchNodes: {
      type: Boolean,
      default: true,
    },
    defaultExpandLevel: {
      type: Number,
      default: 1,
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    // 是否为平坦模式Flat Mode
    /* Flat Mode:
     * Whenever a branch node gets checked, all its children will be checked too
     * Whenever a branch node has all children checked, the branch node itself will be checked too
     */
    isFlat: {
      type: Boolean,
      default: false,
    },
    ifPartyCommittee: {
      type: Boolean,
      default: false,
    },
    // 是否设置默认初始值
    isSetDefaultVal: {
      type: Boolean,
      default: true,
    },
    //除98、99外是否设置抛出值为对象、并抛出值的文本
    isEmitName: {
      type: Boolean,
      default: false,
    },
    parentFunNo: {
      type: Number,
      default: null,
    },
    originTree: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      //绑定树的具体数据
      treeDataOptions: [],
      //选择值
      selectedTree: null,
      //选择的文本
      selectedContent: null,
      //最多显示数据
      limit1: 10,
      //是否显示总数
      showcount: true,
      funNo: null,
      singleStore: {},
    }
  },
  watch: {
    setValue: {
      handler: function (val, oldval) {
        // if (val) {
        //   // //debugger
        //   // let newval = []
        //   // if (!this.selectMultiple) {
        //   //   newval = val.split(',')
        //   // }
        //   if (this.selectMultiple) {
        //     this.selectedTree = newval
        //   } else {
        //     this.selectedTree = newval[0]
        //   }
        // } else {
        //   this.selectedTree = val
        // }
        this.selectedTree = val
      },
      immediate: true,
    },
    selectedTree(val) {
      if (!val) {
        val = null
      }
      this.$emit('updateSelectTreeVal', val)
    },
    selectedContent(val) {
      if (!val) {
        val = null
      }
      if (this.isEmitName) this.$emit('updateSelectTreeContent', val)
    },
  },
  created() {
    if (!this.$route) {
      this.funNo = this.parentFunNo
    } else {
      this.funNo = getFunNo(this.$route)
    }
    this.$nextTick(() => {
      this.singleStore = store.getters.singleStore['main' + this.funNo]
      if (!this.originTree[0]) {
        this.getTreeselect()
      }
    })
  },
  methods: {
    // 选中
    selectTree(item) {
      if (this.selectMultiple) {
        //如果是数组，则追加，不是数组，则创建数组
        if (this.selectedTree == null) this.selectedTree = []
        if (this.selectedContent == null) this.selectedContent = []
        if (this.misTreeType == '99' || this.misTreeType == '98') {
          this.selectedTree.push(item.ctLevelC)
        } else {
          this.selectedTree.push(item.ctCode)
        }
        this.selectedContent.push(item.ctName)
      } else {
        if (this.misTreeType == '99' || this.misTreeType == '98') {
          this.selectedTree = item.ctLevelC
        } else {
          this.selectedTree = item.ctCode
        }
        this.selectedContent = item.ctName
      }
    },
    // 撤销选择
    desselectTree(item) {
      let tempold = this.selectedTree
      let tempcontent = this.selectedContent
      if (this.selectMultiple) {
        if (this.misTreeType == '99' || this.misTreeType == '98') {
          tempold.splice(tempold.indexOf(item.ctLevelC), 1)
        } else {
          tempold.splice(tempold.indexOf(item.ctCode), 1)
        }
        tempcontent.splice(tempcontent.indexOf(item.ctName), 1)
        this.selectedTree = tempold || []
        this.selectedContent = tempcontent || []
      } else {
        this.selectedTree = null
        this.selectedContent = null
      }
    },
    //更多处理
    limitTextValue(count) {
      return `还有 ${count} 个`
    },
    // 提取树数据
    getTreeValue() {
      return request({
        method: 'get',
        url: 'spspublic/treeview/' + this.misTreeType,
      })
    },
    //查询部门下拉树结构
    getTreeselect() {
      if (
        this.singleStore &&
        this.singleStore.handleType &&
        this.singleStore.handleType == 'query'
      ) {
        this.misTreeType = this.misTreeType + 'A'
      }
      this.getTreeValue().then((response) => {
        if (response && response.code === 200 && response.data.length > 0) {
          let data = response.data
          if (this.misTreeType == '133') {
            if (this.ifPartyCommittee) {
              data.forEach((element) => {
                if (element.ctCode == 'HYLX02' || element.ctCode == 'HYLX03') {
                  element.isDisabled = true
                }
              })
            } else {
              data.forEach((element) => {
                if (element.ctCode == 'HYLX01') {
                  element.isDisabled = true
                }
              })
            }
          }
          // console.log("data:", data);
          this.treeDataOptions = this.handleTree(data, 'ctLevelC', 'ctLevelP')

          if (
            (this.misTreeType == '99' || this.misTreeType == '98') &&

            this.isSetDefaultVal
          ) {
            //设置默认值
            if (this.selectedTree == undefined || this.selectedTree == null) {
              this.selectedTree = store.state.user.branchInfo.manageBranchLevel
            }
          }
        }
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      if (this.misTreeType == '99' || this.misTreeType == '98') {
        return {
          id: node.ctLevelC,
          label: node.ctName,
          children: node.children,
        }
      } else {
        return {
          id: node.ctCode,
          label: node.ctName,
          children: node.children,
        }
      }
    },
  },
}
</script>

<style>
[v-cloak] {
  display: none;
}
</style>
